
import axios from 'axios'
import vue from 'vue';
import { ElMessage } from 'element-plus'
import config from "../config"
import { api, lp, getRandom } from "../configs.js";
import sha1 from "js-sha1";
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
         }
         if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
         }
     }
    return "";
} 
// 创建一个独立的axios实例
const service = axios.create({ 
    // 设置baseUr地址,如果通过proxy跨域可直接填写base地址
    baseURL: config.api,
    // 定义统一的请求头部
    // headers: {
    //    "tokenid": "application/x-www-form-urlencoded;charset=UTF-8"
    // },
	headers: {
	   // "tokenid": "nfxcx20220421mao2ctH4NHhSbkZnNPTFLRgtv"  
	},
    // 配置请求超时时间
    timeout: 9999999999999999999999999999999999999999999999999999999999999, 
    // 如果用的JSONP，可以配置此参数带上cookie凭证，如果是代理和CORS不用设置
    withCredentials: true
});

// 请求拦截
service.interceptors.request.use(config => {
    // 自定义header，可添加项目token
	//进度条开始
	    //加密顺序：12随机数  + 时间戳 + 口令
	    let rannumbers = getRandom() + "";
	    let timestamps = new Date().getTime() + "";
	    let signs = sha1(rannumbers+timestamps+lp);
		console.log(lp)
	    if(config.method=='get'){
			config.url+=`?rannumbers=${rannumbers}&timestamps=${timestamps}&signs=${signs}`;
		}else{
		 if (config.data) {
		   
		   if (Object.prototype.toString.call(config.data) != "[object FormData]") {
		     // 不是formdata类型
		     config.data.rannumbers = rannumbers;
		     config.data.timestamps = timestamps;
		     config.data.signs = signs;
		   } else {
		     config.data.append("rannumbers", rannumbers);
		     config.data.append("timestamps", timestamps);
		     config.data.append("signs", signs);
		   }
		 } else {
		   config.data = {};
		   config.data.rannumbers = rannumbers;
		   config.data.timestamps = timestamps;
		   config.data.signs = signs;
		 }	
		}
	    
		
		
    return config;
});
// 返回拦截
service.interceptors.response.use((response)=>{
	//console.log(response)
    // 获取接口返回结果
    const res = response.data;
    // code为0，直接把结果返回回去，这样前端代码就不用在获取一次data.
    if(res.code === 200){
        return res;
    }else if(res.code === 10000){
        // 10000假设是未登录状态码
        ElMessage.warning(res.message);
        // 也可使用router进行跳转
        window.location.href = '/';
        return res;
    }else{
		console.log(res)
        // 错误显示可在service中控制，因为某些场景我们不想要展示错误
         ElMessage.error(res.msg);
        return res;
    }
},()=>{
    ElMessage.error('网络请求异常，请稍后重试!');
});
export default service;